﻿using System;
using System.Collections.Generic;
using MySql.Simple.Mapper.Finders;
using MySql.Simple.Mapper.Structures;

namespace MySql.Simple.Mapper.Commands.Rows
{
    /// <summary>
    /// Reads the contents of a SQL table row into a given object type.
    /// </summary>
    public static class SelectAllCommand
    {
        #region SQL

        private const string Sql = @"SELECT {0} FROM {1};";

        #endregion

        /// <summary>
        /// Reads the contents of a SQL table row into a given object type.
        /// </summary>
        /// <returns></returns>
        public static IList<T> Execute<T>(Connection connection) where T : new()
        {
            // Get SQL ingredients
            var tableName = TableNameFinder.Find(typeof(T));

            // Get columns
            var columns = ColumnFinder.Find(typeof(T));

            // ensure PK is set
            if (columns.HasPrimaryKey)
                throw new ApplicationException("Primary key has not been set on " + typeof(T).Name);

            return connection.ExecuteList<T>(Sql, columns.ToSelectColumnsSql(), tableName);
        }
    }
}